from flask import Blueprint, render_template, request, redirect, url_for, flash
from app.services import directory_scanner

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    """首页"""
    try:
        # 获取库统计信息
        stats = directory_scanner.get_library_stats()
        
        # 获取最近添加的漫画（前8个）
        recent_comics = []
        if directory_scanner.comic_library.comics:
            sorted_comics = sorted(
                directory_scanner.comic_library.comics,
                key=lambda x: x.updated_at,
                reverse=True
            )
            recent_comics = [comic.to_summary_dict() for comic in sorted_comics[:8]]
        
        return render_template('index.html', stats=stats, recent_comics=recent_comics)
        
    except Exception as e:
        flash(f'加载首页时发生错误: {str(e)}', 'error')
        return render_template('index.html', stats={}, recent_comics=[])

@main_bp.route('/comics')
def comic_list():
    """漫画列表页面"""
    try:
        page = request.args.get('page', 1, type=int)
        limit = request.args.get('limit', 20, type=int)
        search = request.args.get('search', '', type=str)
        
        if search:
            # 搜索漫画
            comics = directory_scanner.comic_library.search_comics(search)
            total = len(comics)
            # 手动分页
            start = (page - 1) * limit
            end = start + limit
            comics = comics[start:end]
        else:
            # 获取所有漫画
            comics, total = directory_scanner.comic_library.get_comics(page, limit)
        
        # 转换为摘要格式
        comic_summaries = [comic.to_summary_dict() for comic in comics]
        
        # 计算分页信息
        total_pages = (total + limit - 1) // limit
        has_prev = page > 1
        has_next = page < total_pages
        
        pagination = {
            'page': page,
            'limit': limit,
            'total': total,
            'total_pages': total_pages,
            'has_prev': has_prev,
            'has_next': has_next,
            'prev_num': page - 1 if has_prev else None,
            'next_num': page + 1 if has_next else None
        }
        
        return render_template(
            'comic-list.html',
            comics=comic_summaries,
            pagination=pagination,
            search=search
        )
        
    except Exception as e:
        flash(f'加载漫画列表时发生错误: {str(e)}', 'error')
        return render_template('comic-list.html', comics=[], pagination={}, search='')

@main_bp.route('/comic/<comic_id>')
def comic_detail(comic_id):
    """漫画详情页面"""
    try:
        comic = directory_scanner.comic_library.get_comic(comic_id)
        if not comic:
            flash('漫画不存在', 'error')
            return redirect(url_for('main.comic_list'))
        
        return render_template('comic-detail.html', comic=comic.to_dict())
        
    except Exception as e:
        flash(f'加载漫画详情时发生错误: {str(e)}', 'error')
        return redirect(url_for('main.comic_list'))

@main_bp.route('/reader/<comic_id>')
@main_bp.route('/reader/<comic_id>/<chapter_id>')
@main_bp.route('/reader/<comic_id>/<chapter_id>/<int:page_num>')
def reader(comic_id, chapter_id=None, page_num=1):
    """漫画阅读器"""
    try:
        comic = directory_scanner.comic_library.get_comic(comic_id)
        if not comic:
            flash('漫画不存在', 'error')
            return redirect(url_for('main.comic_list'))
        
        # 如果没有指定章节，使用第一章
        if not chapter_id and comic.chapters:
            chapter_id = comic.chapters[0].id
        
        chapter = comic.get_chapter(chapter_id) if chapter_id else None
        if not chapter:
            if comic.chapters:
                chapter = comic.chapters[0]
                chapter_id = chapter.id
            else:
                flash('没有找到可阅读的章节', 'error')
                return redirect(url_for('main.comic_detail', comic_id=comic_id))
        
        # 验证页码
        if page_num < 1:
            page_num = 1
        elif page_num > chapter.page_count:
            page_num = chapter.page_count
        
        # 获取当前页面
        current_page = chapter.get_page(page_num)
        if not current_page:
            flash('页面不存在', 'error')
            return redirect(url_for('main.comic_detail', comic_id=comic_id))
        
        # 构建阅读器数据
        reader_data = {
            'comic': comic.to_summary_dict(),
            'chapter': chapter.to_dict(),
            'current_page': current_page.to_dict(),
            'page_num': page_num,
            'total_pages': chapter.page_count,
            'has_prev_page': page_num > 1,
            'has_next_page': page_num < chapter.page_count,
            'prev_page_url': url_for('main.reader', comic_id=comic_id, chapter_id=chapter_id, page_num=page_num-1) if page_num > 1 else None,
            'next_page_url': url_for('main.reader', comic_id=comic_id, chapter_id=chapter_id, page_num=page_num+1) if page_num < chapter.page_count else None
        }
        
        # 查找前一章和后一章
        current_chapter_index = next(
            (i for i, ch in enumerate(comic.chapters) if ch.id == chapter_id), 
            0
        )
        
        prev_chapter = comic.chapters[current_chapter_index - 1] if current_chapter_index > 0 else None
        next_chapter = comic.chapters[current_chapter_index + 1] if current_chapter_index < len(comic.chapters) - 1 else None
        
        reader_data.update({
            'prev_chapter': prev_chapter.to_dict() if prev_chapter else None,
            'next_chapter': next_chapter.to_dict() if next_chapter else None,
            'chapter_index': current_chapter_index,
            'total_chapters': len(comic.chapters)
        })
        
        return render_template('reader.html', **reader_data)
        
    except Exception as e:
        flash(f'加载阅读器时发生错误: {str(e)}', 'error')
        return redirect(url_for('main.comic_list'))

@main_bp.route('/scan')
def scan_comics():
    """扫描漫画目录"""
    try:
        force_refresh = request.args.get('force', False, type=bool)
        directory_scanner.scan_comics(force_refresh=force_refresh)
        
        stats = directory_scanner.get_library_stats()
        flash(f'扫描完成！找到 {stats["total_comics"]} 部漫画，{stats["total_chapters"]} 个章节，{stats["total_pages"]} 页', 'success')
        
    except Exception as e:
        flash(f'扫描漫画时发生错误: {str(e)}', 'error')
    
    return redirect(url_for('main.index'))

@main_bp.route('/settings')
def settings():
    """设置页面"""
    try:
        from app.services import cache_manager, image_processor
        
        # 获取统计信息
        library_stats = directory_scanner.get_library_stats()
        cache_stats = cache_manager.get_cache_stats()
        image_cache_stats = image_processor.get_cache_stats()
        
        return render_template(
            'settings.html',
            library_stats=library_stats,
            cache_stats=cache_stats,
            image_cache_stats=image_cache_stats
        )
        
    except Exception as e:
        flash(f'加载设置页面时发生错误: {str(e)}', 'error')
        return redirect(url_for('main.index'))